#include<stdio.h>
#include<stdlib.h>

struct litnode {
    int data;
    struct litnode* next;
};


struct litnode* createnode(int x) {
    struct litnode* newnode = (struct litnode*)malloc(sizeof(struct litnode));
    if (newnode == nullptr)
        perror("malloc fail");
    newnode->next = nullptr;
    newnode->data = x;
    return newnode;


}

int LastRemaining_Solution(int n, int m) {
    // write code here
    int i = 0;
    struct litnode* head = (struct litnode*)malloc(sizeof(struct litnode));
    if (head == nullptr)
        perror("malloc fail");
    head->next =NULL;
    head->data = i++;
    struct litnode* cur = head;
    struct litnode* prev =NULL;
    struct litnode* tail = head;
    while (i <n)
    {
        struct litnode* newnode = createnode(i++);
        tail->next = newnode;
        tail = tail->next;


    }
    tail->next = head;
    int j = 0;
    while (cur->next!= cur)
    {
        if (j == m)
        {
            j = 0;
            prev->next = cur->next;
            free(cur);
            cur = prev->next;



        }
        else {
            prev = cur;
            cur = cur->next;
            j++;

        }










    }
    return cur->data;











}
int main()
{
    int ret = LastRemaining_Solution(5,3);
    printf("%d ", ret);


}
